<template >
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>用户管理</el-breadcrumb-item>
			<el-breadcrumb-item>用户列表</el-breadcrumb-item>
		</el-breadcrumb>
		<!-- 卡片视图>栅格系统包含搜索 -->
		<el-card class="box-card">
			<el-row :gutter="20">
				<el-col :span="8">
					<el-input
						placeholder="请输入内容"
						class="input-with-select"
						v-model="queryInfo.query"
						clearable
						@clear="getUserList"
					>
						<el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
					</el-input>
				</el-col>
				<el-col :span="6">
					<el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
				</el-col>
			</el-row>
			<el-table :data="userlist" stripe border>
				<el-table-column type="index" width="50" :index="index"></el-table-column>
				<el-table-column label="姓名" prop="username"></el-table-column>
				<el-table-column label="邮箱" prop="email"></el-table-column>
				<el-table-column label="电话" prop="mobile"></el-table-column>
				<el-table-column label="角色" prop="role_name"></el-table-column>
				<el-table-column label="状态">
					<template slot-scope="scope">
						<el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
					</template>
				</el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialog(scope.row.id)"></el-button>
						<el-button
							type="danger"
							icon="el-icon-delete"
							size="mini"
							@click="removeUserById(scope.row.id)"
						></el-button>
						<el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
							<el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>
			<!-- 分页部分 -->
			<div class="block">
				<el-pagination
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="queryInfo.pagenum"
					:page-sizes="[3, 5, 10]"
					:page-size="queryInfo.pagesize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="total"
				></el-pagination>
			</div>
		</el-card>

		<!-- 添加用户对话框 -->
		<el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
			<!-- 主题内容 -->
			<el-form
				:model="addForm"
				:rules="addFormRules"
				ref="addFormRef"
				label-width="80px"
				class="demo-ruleForm"
			>
				<el-form-item label="用户名" prop="username">
					<el-input v-model="addForm.username"></el-input>
				</el-form-item>
				<el-form-item label="密码" prop="password">
					<el-input v-model="addForm.password"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="addForm.email"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="mobile">
					<el-input v-model="addForm.mobile"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addUser">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 修改用户对话框 -->
		<el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="resetEditForm">
			<!-- 主题内容 -->
			<el-form
				:model="editForm"
				:rules="addFormRules"
				ref="editFormRef"
				label-width="80px"
				class="demo-ruleForm"
			>
				<el-form-item label="用户名">
					<el-input v-model="editForm.username" :disabled="true"></el-input>
				</el-form-item>

				<el-form-item label="邮箱" prop="email">
					<el-input v-model="editForm.email"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="mobile">
					<el-input v-model="editForm.mobile"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editUser">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 分配角色用户对话框 -->
		<el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="40%" @close="resetSetRole">
			<p>当前用户 : {{userInfo.username}}</p>
			<p>当前角色 : {{userInfo.role_name}}</p>
			<p>
				分配新角色:
				<el-select v-model="selectRoleId" clearable placeholder="请选择">
					<el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
				</el-select>
			</p>

			<span slot="footer" class="dialog-footer">
				<el-button @click="setRoleDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="setRoleCommit(userInfo.id)">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data() {
			// 验证邮箱的规则
			var checkEmail = (rule, value, callback) => {
				// 验证邮箱的正则表达式
				const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;

				if (regEmail.test(value)) {
					// 合法的邮箱
					return callback();
				}
				callback(new Error("请输入合法的邮箱"));
			};

			// 验证手机号的规则
			var checkMobile = (rule, value, callback) => {
				// 验证手机号的正则表达式
				const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
				if (regMobile.test(value)) {
					return callback();
				}
				callback(new Error("请输入合法的手机号"));
			};
			return {
				queryInfo: {
					query: "", // 通过搜索框, 提交的查询参数
					pagenum: 1, // 当前的页数
					pagesize: 3 // 当前每页显示多少条数据
				},
				userlist: [], // 请求用户列表的数据
				total: 0, // 用户列表数据的总条数
				addDialogVisible: false, // 添加用户对话框是否显示
				editDialogVisible: false, // 修改用户对话框是否显示
				addForm: {
					username: "",
					password: "",
					email: "",
					mobile: ""
				},
				addFormRules: {
					username: [
						{ required: true, message: "请输入用户名", trigger: "blur" },
						{
							min: 3,
							max: 11,
							message: "用户名长度为3到16个字符",
							trigger: "blur"
						}
					],
					password: [
						{ required: true, message: "密码长度6--18位", trigger: "blur" },
						{
							min: 3,
							max: 15,
							message: "长度在 3 到 5 个字符",
							trigger: "change"
						}
					],
					email: [
						{ required: true, message: "请输入邮箱", trigger: "blur" },
						{ validator: checkEmail, trigger: "blur" }
					],
					mobile: [
						{ required: true, message: "请输入手机号", trigger: "blur" },
						{ validator: checkMobile, trigger: "blur" }
					]
				},
				editForm: {},
				setRoleDialogVisible: false,
				userInfo: {
					username: "",
					role_name: ""
				},
				roleList: [],
				selectRoleId: ""
			};
		},
		created() {
			this.getUserList();
		},
		computed: {
			// 计算属性,分页后, 列表序号可以接着
			index() {
				return (this.queryInfo.pagenum - 1) * this.queryInfo.pagesize + 1;
			}
		},
		methods: {
			// 获取最新用户列表
			async getUserList() {
				let { data: res } = await this.$http.get("users", {
					params: this.queryInfo
				});
				if (res.meta.status !== 200) {
					return this.$message.error("获取用户列表失败");
				}
				this.userlist = res.data.users;
				this.total = res.data.total;
				// console.log(res);
			},
			handleSizeChange(val) {
				// console.log(`每页 ${val} 条`);
				this.queryInfo.pagesize = val;
				this.getUserList();
			},
			handleCurrentChange(val) {
				// console.log(`当前页: ${val}`);
				this.queryInfo.pagenum = val;
				this.getUserList();
			},
			// 用户状态改变发送请求,
			async userStateChange(userInfo) {
				// console.log(userInfo);
				// 请求路径：users/:uId/state/:type
				let { data: result } = await this.$http.put(
					`users/${userInfo.id}/state/${userInfo.mg_state}`
				);
				console.log(result);
				if (result.meta.status !== 200)
					return this.$message.error("状态修改失败");
				this.$message.success("状态修改成功");
			},
			// 添加用户对话框关闭后,重置表单
			addDialogClosed() {
				this.$refs.addFormRef.resetFields();
			},
			// 添加用户预先校验,校验通过,发送请求
			addUser() {
				// 校验表单
				this.$refs.addFormRef.validate(async valid => {
					if (!valid) return;
					// 表单通过,可以发送请求
					let { data: res } = await this.$http.post("users", this.addForm);
					// 判断状态码
					if (res.meta.status !== 201) return this.$message.error("添加用户失败");
					this.$message.success("添加用户成功");
					// 隐藏对话框
					this.addDialogVisible = false;
					// 重新获取列表
					this.getUserList();
				});
			},
			// 编辑对话框
			async editDialog(id) {
				// console.log(id);
				// 通过传递来的用户id 获取最新的用户信息
				let { data: res } = await this.$http.get("users/" + id);
				// console.log(res);
				if (res.meta.status !== 200) return this.$message.error("获取用户失败");
				this.editForm = res.data;

				// 显示编辑用户对话框
				this.editDialogVisible = true;
			},
			// 编辑用户对话框关闭时,重置
			resetEditForm() {
				this.$refs.editFormRef.resetFields();
			},
			// 编辑用户后, 对话框的验证
			editUser() {
				// console.log(123);
				this.$refs.editFormRef.validate(async valid => {
					// console.log(valid);
					if (!valid) return;
					let { data: res } = await this.$http.put("users/" + this.editForm.id, {
						email: this.editForm.email,
						mobile: this.editForm.mobile
					});
					if (res.meta.status !== 200) return this.$message.error("修改失败");
					// 编辑对话框隐藏
					this.editDialogVisible = false;
					// 重新获取用户列表
					this.getUserList();
					this.$message.success("修改成功");
				});
			},
			// 确认删除

			async removeUserById(id) {
				let result = await this.$confirm(
					"此操作将永久删除该用户, 是否继续?",
					"提示",
					{
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					}
				).catch(err => err);
				// console.log(result);
				if (result !== "confirm") return this.$message.info("已取消删除");
				let { data: res } = await this.$http.delete("users/" + id);
				if (res.meta.status !== 200) return this.$message.error("删除用户失败");
				this.$message.success("删除用户成功");
				this.getUserList();
			},
			async setRole(role) {
				// console.log(role);
				// 展示当前用户信息
				this.userInfo = role;

				// 发送请求,获取 可选择的所有角色
				let { data: res } = await this.$http.get("roles");
				// console.log(res.data);
				this.roleList = res.data;

				this.setRoleDialogVisible = true;
			},
			resetSetRole() {
				this.selectRoleId = "";
			},
			async setRoleCommit(userId) {
				// console.log(userId);
				if (!this.selectRoleId) return this.$message.error("请选新的角色");
				let { data: res } = await this.$http.put(`users/${userId}/role`, {
					rid: this.selectRoleId
				});
				// console.log(res);
				if (res.meta.status !== 200) return this.$message.error("新角色修改失败");
				this.$message.success("修改角色成功");
				this.getUserList();
				this.setRoleDialogVisible = false;
			}
		}
	};
</script>

<style lang="less" scoped>
</style>